<?php
/**
 *
 * Author: TheSmile
 * Date: 2023/5/15 15:37
 * Email: <594652523@qq.com>
 */

namespace App\Console\Commands;

use App\Http\Repositories\Redis\CacheDataRedis;
use App\Models\Campus;
use App\Models\Course;
use App\Models\CourseOrder;
use App\Models\Users;
use EasyWeChat\Factory;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class OrderCancel extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:cancel';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '取消课程';


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
//        Log::info('自动取消任务开始');
        $app        = Factory::miniProgram(config('wechat.mini_program.default'));
        $leftSecond = CacheDataRedis::getRedisInstance()->systemConfig('basic.left_second') ?? 0;
        Course::where('valid', 1)->where('is_cancel', 0)->where('is_condition', 1)->whereIn('id', function ($query) {
            $query->where('begin_time', '>', time())->orderBy('begin_time', 'asc')->select(['id'])->from('course_section');
        })->orderBy('id', 'asc')->chunkById(100, function ($list) use ($leftSecond, $app) {
            foreach ($list as $item) {
                $begin = $this->firstSectionBegin($item['id']);
                $count = $this->success($item['id']);
                $half  = intval(ceil($item['total'] * $item['condition'] * 0.01));
//                Log::info('课程' . $item['id'] . ',报名人数' . $count . '==条件==' . $half . '==最早上课时间==' . date('Y-m-d H:i:s', $begin));
//                $this->info($half.'==='.$count);
//                $this->info(time() + $leftSecond . '===' . $begin);
                if ($begin > time() && time() + $leftSecond > $begin && $half > $count) {//$begin > time() 第一个章节的开始时间必须大于当前时间，否则可能会更改以往的课程
                    $reason              = '报名不足' . $half . '人,自动取消该课程';
                    $item->is_cancel     = 1;
                    $item->cancel_reason = $reason;
                    $item->save();
//                    $this->info('课程' . $item['id'] . '人数不达标取消成功');
                    Log::info('课程' . $item['id'] . '人数不达标取消成功');
                    CourseOrder::where('course_id', $item['id'])->where('status', 2)->chunkById(100, function ($orders) use ($item, $reason, $app) {
                        foreach ($orders as $order) {
                            $order->status        = -1;
                            $order->cancel_reason = $reason;
                            $order->save();
                            $sendData = [
                                'touser'      => Users::where('id', $order['user_id'])->value('openid'),
                                'template_id' => 'HtCd3_f2R2EUBeffKXm_c9YsUz0yg49E-iwA3s1l3Zw',
                                'data'        => [
                                    'thing11' => $item['name'],
                                    'time10'  => $item['class_time'] . ' ' . $item['begin_time'],
                                    'thing3'  => Campus::where('id', $order['campus_id'])->value('address'),
                                    'thing4'  => '人数不足已自动取消，去报名其他课程吧',
                                ],
                                'page'        => 'pages/campus/index'
                            ];

                            //发送给用户对应的关联者
                            $rel = $app->subscribe_message->send($sendData);
                            Log::info('取消课程服务通知结果', ['rel' => json_encode($rel), 'send_data' => json_encode($sendData['data'])]);
                        }
                    });
                }
            }
        });
    }

    //报名成功的订单统计
    public function success($courseId)
    {
        return CourseOrder::where('course_id', $courseId)->where('status', 2)->count();
    }

    public function firstSectionBegin($courseId)
    {
        return DB::table('course_section')->where('course_id', $courseId)->orderBy('begin_time', 'asc')->value('begin_time');
    }

}
